package com.lvhr.rpc.server;

import com.lvhr.rpc.RpcApplication;
import com.lvhr.rpc.model.RpcRequest;
import com.lvhr.rpc.model.RpcResponse;
import com.lvhr.rpc.registry.LocalRegistry;
import com.lvhr.rpc.serializer.JdkSerializer;
import com.lvhr.rpc.serializer.Serializer;
import com.lvhr.rpc.serializer.SerializerFactory;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 * http请求处理
 */
public class HttpServerHandler implements Handler<HttpServerRequest> {

/*    @Override
    public void handle(HttpServerRequest request) {
        //指定序列化器
        final Serializer serializer = new JdkSerializer();

        //记录日志
        System.out.println("Received request: " + request.method()+ request.uri());

        //异步处理，Http请求
        request.bodyHandler(body ->{
            byte[] bytes = body.getBytes();
            RpcRequest rpcRequest = null;

            try {
                rpcRequest = serializer.deSerialize(bytes,RpcRequest.class);
            } catch (IOException e) {
                e.printStackTrace();
            }

            //构造响应结果对象
            RpcResponse rpcResponse = new RpcResponse();

            if(rpcRequest == null){
                rpcResponse.setMessage("rpcRequest is null !");
                doResponse(request,rpcResponse,serializer);
                return;
            }
            try {
                //获取要调用的服务实现类，，通过反射调用
                Class<?> impClass = LocalRegistry.get(rpcRequest.getServiceName());
                Method method = impClass.getMethod(rpcRequest.getMethodName(),rpcRequest.getParameterTypes());
                Object result = method.invoke(impClass.newInstance(),rpcRequest.getArgs());
                //封装返回结果
                rpcResponse.setData(result);
                rpcResponse.setDataType(method.getReturnType());
                rpcResponse.setMessage("ok");
            }
            catch (Exception e){
                e.printStackTrace();
                rpcResponse.setMessage(e.getMessage());
                rpcResponse.setException(e);
            }

            //响应
            doResponse(request,rpcResponse,serializer);
        });
    }*/

    /**
     * 请求处理
     * @param request
     */
    @Override
    public void handle(HttpServerRequest request) {
        //指定序列化器
        final Serializer serializer = SerializerFactory.getInstance(RpcApplication.getRpcConfig().getSerializer());

//        final Serializer serializer = new JdkSerializer();
        //记录日志
        System.out.println("Received request: " + request.method() + request.uri());

        //异步处理http请求
        request.bodyHandler(body -> {
            byte[] bytes = body.getBytes();
            RpcRequest rpcRequest = null;

            try {
                rpcRequest = serializer.deserialize(bytes, RpcRequest.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //构造响应结果对象
            RpcResponse rpcResponse = new RpcResponse();

            if (rpcRequest == null) {
                rpcResponse.setMessage("rpcRequest is null !");
                doResponse(request, rpcResponse, serializer);
                return;
            }

            try {
                // 获取服务实现类
                Class<?> impClass = LocalRegistry.get(rpcRequest.getServiceName());

                // 通过构造函数创建实例（替代已弃用的 newInstance）
                Object serviceInstance = impClass.getDeclaredConstructor().newInstance();
//                Object service = ServiceFactory.getService(interfaceClass);
                // 获取并调用方法
                Method method = impClass.getMethod(
                        rpcRequest.getMethodName(),
                        rpcRequest.getParameterTypes()
                );
                Object result = method.invoke(serviceInstance, rpcRequest.getArgs());

                // 封装响应
                rpcResponse.setData(result);
                rpcResponse.setDataType(method.getReturnType());
                rpcResponse.setMessage("ok");
            } catch (NoSuchMethodException e) {
                // 明确处理无参构造函数不存在的情况
                rpcResponse.setMessage("No accessible no-arg constructor found");
                rpcResponse.setException(e);
            } catch (InstantiationException e) {
                // 处理抽象类/接口实例化异常
                rpcResponse.setMessage("Cannot instantiate abstract class");
                rpcResponse.setException(e);
            } catch (Exception e) { // 其他异常统一处理
                rpcResponse.setMessage(e.getCause() != null ?
                        e.getCause().getMessage() : e.getMessage());
                rpcResponse.setException(e);
            }

            doResponse(request, rpcResponse, serializer);
        });
    }

    /**
     * 响应
     * @param request
     * @param rpcResponse
     * @param serializer
     */
    void doResponse(HttpServerRequest request,RpcResponse rpcResponse,Serializer serializer){

        HttpServerResponse httpServerResponse = request.response().putHeader("Content-type","application/json");
        try{
            //序列化
            byte[] serialized = serializer.serialize(rpcResponse);
            httpServerResponse.end(Buffer.buffer(serialized));
        }catch (IOException e){
            e.printStackTrace();
            httpServerResponse.end(Buffer.buffer());
        }

    }

     /* try {
                // 获取服务实现类
                Class<?> impClass = LocalRegistry.get(rpcRequest.getServiceName());
                // 显式获取无参构造器
                Constructor<?> constructor = impClass.getDeclaredConstructor();  // 关键修改
                Object instance = constructor.newInstance();                    // 关键修改

                // 通过反射调用方法
                Method method = impClass.getMethod(
                        rpcRequest.getMethodName(),
                        rpcRequest.getParameterTypes()
                );
                Object result = method.invoke(instance, rpcRequest.getArgs());  // 使用构造器创建的实例

                // 封装响应
                rpcResponse.setData(result);
                rpcResponse.setDataType(method.getReturnType());
                rpcResponse.setMessage("ok");
            }
            catch (NoSuchMethodException e) {
                // 处理无默认构造器的情况
                throw new RuntimeException("Class "  + " 缺少无参构造函数", e);
            }
            catch (InvocationTargetException e) {
                // 处理构造器或方法抛出的异常
                Throwable cause = e.getCause();
                throw new RuntimeException("调用失败: " + cause.getMessage(), cause);
            }
            catch (InstantiationException | IllegalAccessException e) {
                // 处理访问权限问题
                throw new RuntimeException("无法实例化类: " , e);
            }
*/
}
